<template>
    <el-button v-if="flag" @click="sentCaptcha" :disabled="!disabled" type="warning">发送验证码</el-button>
    <el-button v-else :disabled="true" type="default">{{ count }}S 后发送
    </el-button>
</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue'
import { reg } from '../utils/validate'
import { Http } from '../api/api'
import { ShowError, ShowSuccess } from '../utils/message'
const limit = 180;
const flag = ref<Boolean>(true)
const count = ref<number>(limit)
const toggle = ref<Boolean>(false)
let timer: any = null;

interface PropsTypes {
    phone: String
}
const props: any = defineProps({
    phone: {
        type: [String]
    }
})

const disabled = computed(() => {
    return reg.phone.test(props.phone)
})

watch(props, (v) => {
    console.log(v)
    toggle.value = reg.phone.test(props.phone)
})

const timeDown = () => {
    flag.value = false;
    count.value--;
    timer = setInterval(() => {
        if (count.value > 0) {
            flag.value = false;
            count.value--;
        } else {
            clearInterval(timer)
            timer = null;
            flag.value = true;
            count.value = limit;
        }
    }, 1000)
}

onUnmounted(() => {
    clearInterval(timer)
    timer = null;
})

const sentCaptcha = async () => {
    let res = await Http.chechphone({ phone: props.phone }) as unknown as any;
    if (res.code == 200) {
        timeDown()

        Http.captchaSent({ phone: props.phone })
            .then((result: any) => {
                console.log(result)
                if (result.data) {
                    ShowSuccess('验证码发送成功')
                } else {
                    ShowError('验证码发送失败')
                }
            })
            .catch(err => {
                ShowError('手机每天最多发送5条验证码')
            })
    }
}
</script>